#include "SwitchButton.h"
#include <QStylePainter>
#include <QStyleOption>
#include <QMouseEvent>
#include <QtDebug>
#include <QLayout>
#include <chrono>

SwitchButton::SwitchButton(bool on, QWidget* parent)
	: QWidget(parent)
{
	m_switchOn = on;
	m_scaleFactor = 1;
	initButton();
}

QSize SwitchButton::sizeHint() const
{
	bool inLayout = false;
	QObject* parent = this->parent();
	QWidget* pw = qobject_cast<QWidget*>(parent);
	if(qobject_cast<QLayout*>(parent) || (pw && pw->layout() && pw->layout()->indexOf(const_cast<SwitchButton*>(this)) != -1))
		inLayout = true;
	float scale = inLayout ? m_scaleFactor : 1;
	return QSize(50, 22) * scale;
}

void SwitchButton::initButton()
{
	setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
	connect(this, &SwitchButton::switchChanged, this, QOverload<>::of(&QWidget::update));
}

void SwitchButton::paintEvent(QPaintEvent* event)
{
	QStylePainter painter(this);
	painter.setRenderHint(QPainter::Antialiasing);

	QColor bkColor(0x13, 0x6c, 0x5e);
	QColor txtColor(0xFF, 0xEB, 0xC8);
	QColor switchColor(0xFF, 0xEB, 0xC8);

	if (!m_switchOn)
	{
		bkColor.setRgb(0x4A, 0x4B, 0x4C);
		switchColor.setRgb(0x8F, 0x95, 0x98);
	}
	//draw the background
	QPainterPath border;
	QRectF r(0, 0, width(), height());
	border.addRoundedRect(r, 10.0 * m_scaleFactor, 10.0 * m_scaleFactor);
	painter.setPen(Qt::NoPen);
	painter.setBrush(QBrush(bkColor));
	painter.drawPath(border);

	//draw text
	painter.setPen(txtColor);
	painter.setBrush(Qt::NoBrush);

	QFont font = painter.font(); 
	font.setPixelSize(12);
	painter.setFont(font);
	
	/*
	auto start = std::chrono::system_clock::now();
	QFontMetrics& qm = painter.fontMetrics();
	QRectF tightRect = qm.tightBoundingRect(tr("开关"));//Warning: Slow in windows
	auto end = std::chrono::system_clock::now();
	qDebug() << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
	float offset = height() / 2 - tightRect.center().y();
	painter.drawText((m_switchOn ? 31/2.0 : 19 + 31/2.0) * m_scaleFactor - tightRect.center().x(), offset, m_switchOn ? tr("开关") : tr("关"));
	*/
	painter.scale(m_scaleFactor, m_scaleFactor);//TODO:GET this value from CFG
	
	QRect txtRect(m_switchOn ? 0 : 19, 0, 31, 22);
	painter.drawText(txtRect, Qt::AlignCenter, m_switchOn ? tr("开") : tr("关"));

	//draw switch
	painter.setPen(Qt::NoPen);
	painter.setBrush(QBrush(switchColor));
	painter.drawEllipse(QPoint(m_switchOn ? 38 : 12, 11), 7, 7);
}

void SwitchButton::mouseReleaseEvent(QMouseEvent* e)
{
	QRegion qr((m_switchOn ? 31 : 5) * m_scaleFactor, 5 * m_scaleFactor, 14 * m_scaleFactor, 14 * m_scaleFactor, QRegion::Ellipse);
	if (qr.contains(e->pos()))
	{
		m_switchOn = !m_switchOn;
		switchChanged(m_switchOn);
	}
}
